<template>
  <!--  <div>-->
  <div class="canvas-wrapper">
    <div class="canvas-container">
<!--          <canvas id="myCanvas" width="1200px" height="565.6px" @mousemove="updateXY"  border="2px solid red;"></canvas>-->
      <canvas id="backgroundCanvas" width="1500" height="680"></canvas>
      <canvas id="myCanvas" width="1500" height="680" @mousemove="updateXY"></canvas>
      <div v-if="showTooltip" :style="{top: tooltipY + 'px', left: tooltipX + 'px'}" class="tooltip">
        {{ tooltipContent }}
        <!--    {{ formattedTooltipContent(tooltipContent) }}-->
      </div>
    </div>
  </div>
  <!--    <canvas id="myCanvas" width="3268" height="1480" @mousemove="updateXY"  border="2px solid red;"></canvas>-->
  <!--  </div>-->
</template>

<script>
  import AddOrUpdate from './wmpos-add-or-update'
  export default {
    data () {
      return {
        timer: null,
        dataForm: {
          key: ''
        },
        x: 0,
        y: 0,
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        enabledMapLocalpaths: '',
        showTooltip: false,
        tooltipX: 0,
        tooltipY: 0,
        tooltipContent: '',
        oldDataListInfo: [],  // 用于保存前一个状态的数据
      }
    },
    components: {
      AddOrUpdate
    },
    mounted () {
      // this.showPosInfoData()

      this.renderBackgroundCanvas();
      // 页面加载后
      // 1.在执行定时器前先执行一次获取接口数据的操作函数, 否则接口会1秒钟后才调用
      // 2.为了避免退出当前页面后,在其他页面也继续调用接口,退出前需要清除定时器.
      this.show();

      // 每 3 秒执行一次 show 方法
      // this.timer = setInterval(() => {
      //   this.show();
      // }, 3000);
      // this.timer = setInterval(() => {
      //   setTimeout(this.show, 0)
      // }, 20000)
    },
    beforeRouteLeave (to, from, next) {
      // 在离开当前路由之前清除定时器
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
      next();
    },
    activated () {
      this.dataListLoading = true;
      // 在另一个页面中获取已启用地图的mapLocalpaths
      this.enabledMapLocalpaths = JSON.parse(localStorage.getItem('enabledMapLocalpaths'));
      // console.log("enabledMapLocalpaths")
      // console.log(this.enabledMapLocalpaths); // 这里将会输出所有已启用地图的mapLocalpath数组
      // this.show()
      this.dataListLoading = false;
    },
    methods: {
      //测试ws数据
      showPosInfoData(){
        // let URL = "ws://10.143.7.73:8089/renren-fast/websocket/font";
        let URL = "ws://localhost:8089/renren-fast/websocket/allPosInfo";
        let ws = new WebSocket(URL);
        ws.onmessage = evt => {    //后端发来的消息接收（注意数据放在evt的data中并且是个JSON字符串，需要parse成JSON对象去使用）
          //let hhlist = JSON.parse(evt);

          console.log("接收中。。。")
          console.log(evt.data)
          //evt.data格式为：{"板材切割中心3#切割机.deviceProcessStatus":"6","板材切割中心3#切割机.deviceCutStatus":"1","板材切割中心3#切割机.deviceMachineSpeed":"0","板材切割中心3#切割机.deviceLocation":"0","板材切割中心3#切割机.deviceStatus":"0"}
          console.log('接收完成')
          //具体业务逻辑
          const messageData = JSON.parse(evt.data);
          this.updateMessageData(messageData);

        }
        ws.onclose = function () {
          // 关闭 websocket
          console.log('连接已关闭...')
        }
        // 路由跳转时结束websocket链接
        this.$router.afterEach(function () {
          ws.close()
        })
      },
      renderBackgroundCanvas() {
        const c = document.getElementById('backgroundCanvas');
        const ctx = c.getContext('2d');
        const img = new Image();
        img.src = this.enabledMapLocalpaths;
        img.onload = function() {
          ctx.drawImage(img, 0, 0, c.width, c.height);
        };
      },
      updateXY (event) {
        this.x = event.offsetX;
        this.y = event.offsetY;
        this.checkPointNearby(event.target);
      },
      checkPointNearby (target) {
        for (let point of this.dataListInfo) {
          const distance = Math.sqrt(Math.pow((this.x - point.posx), 2) + Math.pow((this.y - point.posy), 2));
          if (distance <= 5) { // 根据你的点的大小，5可能需要调整
            this.showTooltip = true;
            this.tooltipX = this.x + 10; // 在鼠标右侧稍微偏移
            this.tooltipY = this.y + 10; // 在鼠标下方稍微偏移
            this.tooltipContent = `设备编号: ${point.id}\n设备名称: ${point.name}`;
            target.style.cursor = 'pointer'; // 直接在此设置鼠标样式
            return;
          }
        }
        this.showTooltip = false;  // 如果没有点在附近，隐藏tooltip
        target.style.cursor = 'default'; // 直接在此设置鼠标样式
      },
      show () {
        // this.getArea()
        this.dataListLoading = true;
        this.$http({
          url: this.$http.adornUrl('/cutpos/cutpos/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'key': this.dataForm.key
          })
        }).then(({data}) => {
          console.log(data)
          this.oldDataListInfo = this.dataListInfo; // 保存旧数据
          this.dataListInfo = data.page.list;
          console.log(this.oldDataListInfo)
          console.log(this.dataListInfo)
          // this.areaList = data.page.list
          // console.log('ok')
          var json = data.page.list;
          console.log(json)
          //切割机数据
          var query1 = json.filter(function (i) {
            return i.type == 1;
          })
          console.log(query1)
          //焊机数据
          var query2 = json.filter(function (i) {
            return i.type == 2;
          })
          // console.log(query2

          var arr = [];
          for (let i in query1) {
            arr.push(query1[i]);
          }
          var posx = arr.map(item => {
            // 每一项的id
            return item.posx
          });
          var posy = arr.map(item => {
            // 每一项的id
            return item.posy
          });
          // console.log(posx)

          var arr2 = [];
          for (let i in query2) {
            arr2.push(query2[i]);
          }
          var posx1 = arr2.map(item => {
            // 每一项的id
            return item.posx
          });
          var posy1 = arr2.map(item => {
            // 每一项的id
            return item.posy
          });
          // console.log(posx1)

          var c = document.getElementById('myCanvas');
          const img = new Image();

          const ctx = c.getContext('2d');
          ctx.strokeStyle = '#0000ff';

          // 动手
          // img.src = 'static/images/3.jpg';
          img.src = this.enabledMapLocalpaths;
          // 当图片加载完再动手
          img.onload = function () {
            // 画布大小和图片尺寸不一样算好比例
            const cWidth = c.width;
            const cHeight = c.height;
            const imgWidth = img.naturalWidth;
            const imgHeight = img.naturalHeight;
            // console.log("img")
            // console.log(imgWidth)
            // console.log(imgHeight)
            const zoom = {
              width: cWidth / imgWidth,
              height: cHeight / imgHeight
            };
            // 以图画底
            ctx.drawImage(img, 0, 0, cWidth, cHeight);
            for (var i = 0; i < posx.length; i++) {
              ctx.fillStyle = '#00FF00';
              ctx.beginPath();
              ctx.arc(posx[i] * zoom.width, posy[i] * zoom.height, 5, 0, 2 * Math.PI);
              ctx.fill();
            }
            ;
            for (var j = 0; j < posx1.length; j++) {
              ctx.fillStyle = '#FF0000';
              ctx.beginPath();
              ctx.arc(posx1[j] * zoom.width, posy1[j] * zoom.height, 5, 0, 2 * Math.PI);
              ctx.fill();
            }
            ;
          };
          // this.animatePoints();
        })
        this.dataListLoading = false;
      },
      // animatePoints() {
      //   const duration = 2000; // 动画持续时间为1000ms
      //   let startTime = null;
      //
      //   const c = document.getElementById('myCanvas');
      //   const ctx = c.getContext('2d');
      //   const img = new Image();
      //   img.src = this.enabledMapLocalpaths;
      //
      //   const cWidth = c.width;
      //   const cHeight = c.height;
      //   const imgWidth = img.naturalWidth;
      //   const imgHeight = img.naturalHeight;
      //   const zoom = {
      //     width: cWidth / imgWidth,
      //     height: cHeight / imgHeight
      //   };
      //
      //   const step = (timestamp) => {
      //     if (!startTime) startTime = timestamp;
      //     let progress = (timestamp - startTime) / duration;
      //     if (progress > 1) progress = 1;
      //
      //     ctx.clearRect(0, 0, c.width, c.height);
      //
      //     // 重新渲染背景图像
      //     ctx.drawImage(img, 0, 0, cWidth, cHeight);
      //
      //     for (const point of this.dataListInfo) {
      //       const oldPoint = this.oldDataListInfo.find(p => p.uuid === point.uuid) || point;
      //       const currentX = oldPoint.posX + (point.posX - oldPoint.posX) * progress;
      //       const currentY = oldPoint.posY + (point.posY - oldPoint.posY) * progress;
      //
      //       ctx.beginPath();
      //       if (point.type == 1) {
      //         ctx.fillStyle = '#00FF00';
      //       } else if (point.type == 2) {
      //         ctx.fillStyle = '#FF0000';
      //       } else {
      //         ctx.fillStyle = '#FFD306';
      //       }
      //       ctx.arc(currentX * zoom.width, currentY * zoom.height, 5, 0, 2 * Math.PI);
      //       ctx.fill();
      //     }
      //
      //     if (progress < 1) {
      //       requestAnimationFrame(step);
      //     }
      //   };
      //
      //   img.onload = () => {
      //     requestAnimationFrame(step);
      //   };
      // },
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/wmpos/wmpos/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'key': this.dataForm.key
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/wmpos/wmpos/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      }
    }
  }
</script>
<style scoped>
* {
  margin: 0;
  padding: 0;
}
#myCanvas {
  /*max-width: 100%;*/
  /*max-height: 100%;*/
  /*width:auto;*/
  /*height:auto;*/
}
.canvas-container {
  position: relative;
  width: 1500px;
  height: 680px;
}

.tooltip {
  position: absolute;
  background-color: white;
  border: 1px solid #ccc;
  padding: 5px;
  z-index: 1000;
  pointer-events: none;
  white-space: nowrap; /* 防止内容换行 */
}

#backgroundCanvas, #myCanvas {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
}

#myCanvas {
  z-index: 2;
}



</style>
